//
//  LBSegmentControl.m
//

#import "LBSegmentControl.h"

#define BUTTON_Tag 100

#define TRUNK_TAG 230

@interface LBSegmentControl()

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIButton *lastBtn;

@property (nonatomic, strong) UIView *sliderView;

@property (nonatomic, strong) UIView *bottomLine;

@end

@implementation LBSegmentControl{
    __weak id _target;
    SEL _action;
}

#pragma mark - 通过items创建初始化分段选择器
- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        _contentInsets = UIEdgeInsetsZero;
        _selectedColor = [UIColor blackColor];
        _normalColor = kDarkGrayColor;
        _trunkTintColor = [UIColor blackColor];
        _trunkCornerRadius = CGRectGetHeight(frame) / 2.0f;
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
        
    }
    
    return self;
}

#pragma mark - 重写选中下标的set方法
- (void)setSelectedSegmentIndex:(NSUInteger)selectedSegmentIndex{
    
    UIButton * btn1 = (UIButton *)[self viewWithTag:_selectedSegmentIndex + BUTTON_Tag];
    btn1.userInteractionEnabled = YES;
    btn1.selected = NO;
    btn1.titleLabel.font = lbFont(self.normalFont?:14);
    
    _selectedSegmentIndex = selectedSegmentIndex;
    
    UIButton * btn = (UIButton *)[self viewWithTag:_selectedSegmentIndex + BUTTON_Tag];
    btn.titleLabel.font = lbFont(self.selectFont?:self.normalFont?:15);
    btn.selected = YES;
    
    btn.userInteractionEnabled = NO;
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3f animations:^{
        [weakSelf updateTrunkAndBottomLineSpaceWithBtn:btn];
    }];
    if (self.scrollView.contentSize.width < lbScreenWidth) {
        return;
    }
    // 改变当前scrollView的偏移量
    if (self.items.count > 4) {
        if (btn.center.x - self.width / 2.0f > 0 && self.scrollView.contentSize.width - btn.center.x > self.width / 2.0f) {
            
            [self.scrollView setContentOffset:CGPointMake(btn.center.x - self.width / 2.0f, 0) animated:YES];
        } else {
            
            if (btn.center.x - self.width / 2.0f <= 0) {
                [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            if (self.scrollView.contentSize.width - btn.center.x <= self.width / 2.0f) {
                [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentSize.width - self.width, 0) animated:YES];
            }
        }
    }
}

- (void)updateTrunkAndBottomLineSpaceWithBtn:(UIButton *)btn{
    if (self.showTrunk) {
        _sliderView.frame = CGRectMake(btn.frame.origin.x - 20, 0, CGRectGetWidth(btn.frame) + 40, CGRectGetHeight(self.frame));
    }
    if (self.showBottomLine) {
        _bottomLine.frame = CGRectMake(_lineWidth?btn.frame.origin.x + (btn.width - _lineWidth)/2:btn.frame.origin.x, self.height - 2, _lineWidth?:btn.width, 2);
    }
}

#pragma mark - 创建按钮
//通过items去创建按钮
- (void)createButton{
    
    _lastBtn = nil;
    CGFloat H = self.height;
    
    CGFloat Y = 0;
    
    CGFloat margin = 18;
    
    UIButton * firstBtn;
    
    int  i = 0;
    for (NSString * title in _items) {
        CGFloat W;
        if (self.showCount) {
            W = lbScreenWidth/self.showCount;
            margin = 0;
        }else{
            W = [title sizeWithFont:[UIFont systemFontOfSize:18]].width;
        }
        
        CGFloat X = _lastBtn.frame.origin.x + CGRectGetWidth(_lastBtn.frame) + margin;
        
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(X, Y, W, H)];
        
        [button setTitle:title forState:UIControlStateNormal];
        
        [button setTitleColor:_normalColor forState:UIControlStateNormal];
        
        [button setTitleColor:_selectedColor forState:UIControlStateSelected];
        
        [button.titleLabel setFont:lbFont(self.normalFont?:15)];
        
        [button addTarget:self action:@selector(onclicked:) forControlEvents:UIControlEventTouchUpInside];
        
        button.tag = i + BUTTON_Tag;
        
        if (i == 0) {
            firstBtn = button;
        }
        [_scrollView addSubview:button];
        
        _lastBtn = button;
        
        i++;
    }
    
    _contentWidth = CGRectGetMaxX(_lastBtn.frame);
    
    _scrollView.contentSize = CGSizeMake(CGRectGetWidth(_lastBtn.frame) + _lastBtn.frame.origin.x + margin, _lastBtn.frame.size.height);
    
    CGFloat SW = 20;
    CGFloat SH = 2;
    
    if (_showTrunk) {
        _sliderView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - SH, SW, SH)];
        _sliderView.layer.borderColor = [UIColor blackColor].CGColor;
        _sliderView.backgroundColor = _trunkTintColor;
        _sliderView.layer.borderWidth = 1;
        _sliderView.tag = TRUNK_TAG;
        _sliderView.frame = CGRectMake(firstBtn.frame.origin.x - 20, 0, CGRectGetWidth(firstBtn.frame) + 40, CGRectGetHeight(self.frame));
        _sliderView.layer.cornerRadius = CGRectGetHeight(self.frame) / 2.0f;
        [_scrollView insertSubview:_sliderView belowSubview:firstBtn];
    }
    
    if (_showBottomLine) {
        _bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _bottomLine.backgroundColor = _trunkTintColor?:[UIColor blackColor];
        _bottomLine.frame = CGRectMake(_lineWidth?firstBtn.frame.origin.x + (firstBtn.width - _lineWidth)/2:firstBtn.frame.origin.x, self.height - 2, _lineWidth?:firstBtn.width, 2);
        [_scrollView addSubview:_bottomLine];
    }
}

#pragma mark - 按钮点击
- (void)onclicked:(UIButton *)button{
    
    //好方法:
    //通过选中下标拿到当前选中的按钮
    UIButton * selectedBtn = (UIButton *)[self viewWithTag:_selectedSegmentIndex + BUTTON_Tag];
    //将之前选中的变成非选中状态
    selectedBtn.selected = NO;
    
    selectedBtn.userInteractionEnabled = YES;
    
    self.selectedSegmentIndex = button.tag - BUTTON_Tag;
    
    if ([_target respondsToSelector:_action]) {
        [_target performSelector:_action withObject:self];
    }else{
        
        NSLog(@"警告:事件方法没有实现");
    }
    
}

#pragma mark - 添加事件
- (void)addTarget:(id)target action:(SEL)action{
    _target = target;
    _action = action;
}

- (void)setItems:(NSArray *)items {
    
    _items = items;
    
    for (UIView *view in self.scrollView.subviews) {
        
        if ([view isKindOfClass:[UIButton class]] || view.tag == TRUNK_TAG) {
            
            [view removeFromSuperview];
        }
        
    }
    [self.sliderView removeFromSuperview];
    [self.bottomLine removeFromSuperview];
    [self createButton];
    self.selectedSegmentIndex = _selectedSegmentIndex;
}

- (void)contentOffset{
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
}


@end
